<style lang="less">
// @import "./departmentManage.less";
</style>
<template>
  <div class="search">
    <Card>
      <Row class="operation">
        <Button @click="add" type="primary" icon="md-add">添加子分类</Button>
        <Button @click="addRoot" icon="md-add">添加一级分类</Button>
        <Button @click="delAll" icon="md-trash">删除</Button>
        <Button @click="getParentList" icon="md-refresh">刷新</Button>
        <i-switch v-model="strict" size="large" style="margin-left:5px">
          <span slot="open">级联</span>
          <span slot="close">单选</span>
        </i-switch>
      </Row>
      <Row type="flex" justify="start" class="code-row-bg">
        <Col span="6">
          <Alert show-icon>
            当前选择编辑：
            <span class="select-title">{{editTitle}}</span>
            <a class="select-clear" v-if="form.id" @click="cancelEdit">取消选择</a>
          </Alert>
          <div class="tree-bar" :style="{maxHeight: maxHeight}">
            <Tree
              ref="tree"
              :data="data"
              :load-data="loadData"
              disableCheckbox
              @on-check-change="changeSelect"
              @on-select-change="selectTree"
              :check-strictly="!strict"
            ></Tree>
          </div>
          <Spin size="large" fix v-if="loading"></Spin>
        </Col>
        <Col span="9" style="margin-left:10px">
          <Form ref="form" :model="form" :label-width="85" :rules="formValidate">
            <FormItem label="分类名称" prop="title">
              <Input v-model="form.title"/>
            </FormItem>
            <FormItem label="分类图片" prop="pic">
                <upload-pic-input v-model="form.pic" style="width:100%"></upload-pic-input>
            </FormItem>
            <FormItem label="购买状态" prop="buyState" v-if="form.parentId != '0'">
              <Select v-model="form.buyState" style="width: 100%">
                <Option value="1">直接购买</Option>
                <Option value="2">租赁</Option>
                <Option value="3">租赁和购买</Option>
              </Select>
            </FormItem>
            <FormItem label="租赁状态" prop="leaseState" v-if="form.parentId != '0'">
              <Select v-model="form.leaseState" style="width: 100%">
                <Option value="1">尾款线上支付</Option>
                <Option value="2">尾款线下支付</Option>
              </Select>
            </FormItem>
            <FormItem label="排序值" prop="sortOrder">
              <InputNumber :max="1000" :min="0" v-model="form.sortOrder"></InputNumber>
              <span style="margin-left:5px">值越小越靠前，支持小数</span>
            </FormItem>
            <FormItem label="是否启用" prop="status">
              <RadioGroup v-model="form.status">
                <Radio label="0">是</Radio>
                <Radio label="-1">否</Radio>
              </RadioGroup>
            </FormItem>
            <Form-item>
              <Button
                style="margin-right:5px"
                @click="submitEdit"
                :loading="submitLoading"
                type="primary"
                icon="ios-create-outline"
              >修改并保存</Button>
              <Button @click="handleReset">重置</Button>
            </Form-item>
          </Form>
        </Col>
      </Row>
    </Card>

    <Modal :title="modalTitle" v-model="modalVisible" :mask-closable="false" :width="500">
        <Form ref="formAdd" :model="formAdd" :label-width="85" :rules="formValidate">
            <div v-if="showParent">
              <FormItem label="上级分类：">{{form.title}}</FormItem>
            </div>
            <FormItem label="分类名称" prop="title">
              <Input v-model="formAdd.title"/>
            </FormItem>
            <FormItem label="分类图片" prop="pic">
              <upload-pic-input v-model="formAdd.pic" style="width:100%"></upload-pic-input>
            </FormItem>
            <FormItem label="购买状态" prop="buyState" v-if="showParent">
              <Select v-model="formAdd.buyState" style="width: 100%">
                <Option value="1">直接购买</Option>
                <Option value="2">租赁</Option>
                <Option value="3">租赁和购买</Option>
              </Select>
            </FormItem>
            <FormItem label="租赁状态" prop="leaseState" v-if="showParent">
              <Select v-model="formAdd.leaseState" style="width: 100%">
                <Option value="1">尾款线上支付</Option>
                <Option value="2">尾款线下支付</Option>
              </Select>
            </FormItem>
            <FormItem label="排序值" prop="sortOrder">
              <InputNumber :max="1000" :min="0" v-model="formAdd.sortOrder"></InputNumber>
              <span style="margin-left:5px">值越小越靠前，支持小数</span>
            </FormItem>
            <FormItem label="是否启用" prop="status">
              <RadioGroup v-model="formAdd.status">
                <Radio label="0">是</Radio>
                <Radio label="-1">否</Radio>
              </RadioGroup>
            </FormItem>
        </Form>
        <div slot="footer">
            <Button type="text" @click="cancelAdd">取消</Button>
            <Button type="primary" :loading="submitLoading" @click="submitAdd">提交</Button>
        </div>
    </Modal>
  </div>
</template>

<script>
import uploadPicInput from "@/views/my-components/xboot/upload-pic-input";
import{ getCategoryList, editCategory, addCategory, removeCategory } from '@/api/commodity'
export default {
  name: "classify-manage",
  components: {
      uploadPicInput
  },
  data() {
    return {
        loading: true,
        maxHeight: "500px",
        strict: true,
        userLoading: false,
        loadingEdit: true,
        modalVisible: false,
        showParent: false,
        modalTitle: "",
        editTitle: "",
        form: {
            id: "",
            title: "",
            parentId: "",
            parentTitle: "",
            sortOrder: 0,
            type: 0,
            pic: "",
            status: "0",
            buyState: "",
            leaseState: ""
        },
        searchForm:{
            pid: "",
        },
        formAdd: {},
        formValidate: {
          title: [{ required: true, message: "请输入名称", trigger: "blur" }],
          pic: [{ required: true, message: "请选择图片", trigger: "blur" }],
          buyState: [{ required: true, message: "请选择购买状态", trigger: "change" }],
          leaseState: [{ required: true, message: "请选择租赁状态", trigger: "change" }],
        },
        submitLoading: false,
        data: [],
        // dataEdit: [],
        users: []
    };
  },
  methods: {
    init() {
      this.getParentList();
    //   this.getParentListEdit();
    },
    getParentList() {
      this.loading = true;

      getCategoryList().then(res => {
          this.loading = false
          if(res.success) {
              res.result.forEach(function(e) {
                    if (e.isParent) {
                        e.loading = false;
                        e.children = [];
                    }
                });
                this.data = res.result;
          }
      })
    },
    loadData(item, callback) {
      var param = {
        pid: item.id
      }
      getCategoryList(param).then(res => {
        console.log(res)
        this.loading = false;
        if (res.success) {
          res.result.forEach(function(e) {
            if (e.isParent) {
              e.loading = false;
              e.children = [];
            }
          });
          callback(res.result);
        } else {
          this.$Message.warning("该分类下没有数据！")
        }
      })
    },
    selectTree(v) {
      if (v.length > 0) {
        // 转换null为""
        for (let attr in v[0]) {
          if (v[0][attr] == null) {
            v[0][attr] = "";
          }
        }
        let str = JSON.stringify(v[0]);
        let data = JSON.parse(str);
        this.editTitle = data.title;
        // 加载部门用户数据
        this.userLoading = true;
        getCategoryList({
          pid: data.id
        }).then(res => {
          this.userLoading = false;
          if (res.success) {
            this.users = res.result;
          }
        });
        // 回显
        data.status = data.status.toString();
        data.leaseState = data.leaseState.toString();
        data.buyState = data.buyState.toString()
        this.form = data;
      } else {
        this.cancelEdit();
      }
    },
    cancelEdit() {
      let data = this.$refs.tree.getSelectedNodes()[0];
      if (data) {
        data.selected = false;
      }
      this.$refs.form.resetFields();
      delete this.form.id;
      this.editTitle = "";
    },
    cancelAdd() {
      this.modalVisible = false;
    },
    handleReset() {
      this.$refs.form.resetFields();
      this.form.type = 0;
    },
    submitEdit() {
        this.$refs.form.validate(valid => {
            if (valid) {
                if (!this.form.id) {
                    this.$Message.warning("请先点击选择要修改的分类");
                    return;
                }
                this.submitLoading = true;
                editCategory(this.form).then(res => {
                    this.submitLoading = false;
                    if (res.success) {
                        this.$Message.success("编辑成功");
                        this.init();
                        this.modalVisible = false;
                    }
                })
            }
        });
    },
    submitAdd() {
        this.$refs.formAdd.validate(valid => {
            if (valid) {
                this.submitLoading = true;
                addCategory(this.formAdd).then(res => {
                    if (res.success) {
                        this.submitLoading = false;
                        if (res.success) {
                            this.$Message.success("添加成功");
                            this.init();
                            this.modalVisible = false;
                        }
                    }
                })
            }
        });
    },
    add() {
        if (this.form.id == "" || this.form.id == null) {
            this.$Message.warning("请先点击选择一个分类");
            return;
        }
        this.modalTitle = "添加子分类";
        this.showParent = true;
        this.formAdd = {
            parentId: this.form.id,
            sortOrder: 0,
            type: 2,
            status: "0"
        };
        this.modalVisible = true;
    },
    addRoot() {
        this.modalTitle = "添加一级分类";
        this.showParent = false;
        this.formAdd = {
            parentId: "",
            sortOrder: 0,
            type: 2,
            status: "0"
        };
        this.modalVisible = true;
    },
    changeSelect(v) {
        // this.selectCount = v.length;
        // this.selectList = v;
    },
    delAll() {
        if (this.form.id =='') {
            this.$Message.warning("您还未勾选要删除的数据");
            return;
        }
        this.$Modal.confirm({
            title: "确认删除",
            content: "您确认要删除所选的数据?",
            onOk: () => {
                removeCategory({
                    id:this.form.id
                }).then(res => {
                    this.loading = false;
                    if (res.success) {
                        this.submitLoading = false;
                        if (res.success) {
                            this.$Message.success("删除成功");
                            this.cancelEdit();
                            this.init();
                        }
                    }
                })
            }
        });
    }
  },
  mounted() {
    // 计算高度
    let height = document.documentElement.clientHeight;
    this.maxHeight = Number(height - 287) + "px";
    this.init();
  }
};
</script>

<style scoped>
.operation{
    margin-bottom: 18px;
}
</style>